package com.warmlight.voicepacket.adapter;

import android.app.Activity;
import android.content.Context;
import android.os.Handler;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.support.v4.widget.SwipeRefreshLayout;
import android.text.TextUtils;
import android.view.View;
import android.view.ViewGroup;
import android.widget.HeaderViewListAdapter;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;

import com.google.gson.Gson;
import com.warmlight.voicepacket.R;
import com.warmlight.voicepacket.data.RecommendData;
import com.warmlight.voicepacket.data.RecommendFeed;
import com.warmlight.voicepacket.http.Callback;
import com.warmlight.voicepacket.http.HttpClient;
import com.warmlight.voicepacket.http.HttpConfig;
import com.warmlight.voicepacket.utils.SPUtils;
import com.warmlight.voicepacket.widget.CoverLoading;
import com.warmlight.voicepacket.widget.FooterListView;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.TreeMap;

import okhttp3.Call;

import static com.warmlight.voicepacket.http.HttpConfig.DISCOVER_FEED;
import static com.warmlight.voicepacket.http.HttpConfig.SERVER;

/**
 * 发现页面整个 viewpager de adapter
 * Created by jason on 2018/5/21.
 */

public class TopicPagerAdapter extends PagerAdapter {

    private List<RecommendData.DataBean.CategoryBean> mList;
    private Context mContext;
    private RelativeLayout currentRelativeLayout;
//    private static boolean IS_FIRST = true;

    public TopicPagerAdapter(Context context, List<RecommendData.DataBean.CategoryBean> list) {
        mList = list;
        mContext = context;
    }

    @Override
    public int getCount() {
        if (mList == null || mList.size() <= 1) {
            // return mList.size();
            return 1;
        } else {
            return mList.size();
        }
    }

    @Override
    public boolean isViewFromObject(View arg0, Object arg1) {
        return arg0 == arg1;
    }

    @Override
    public void destroyItem(View container, int position, Object object) {
        ((ViewPager) container).removeView((View) object);
    }

    @Override
    public int getItemPosition(Object object) {
        View view = (View) object;
        int tag = (int) view.getTag();
//        if (mCurrentItem == tag){
//            mCurrentItem = -1;
//            return POSITION_NONE;
//        }else
        if (mCurrentitemleft == tag){
            mCurrentitemleft = -1;
            return POSITION_NONE;
        }else if (mCurrentItemRight == tag){
            mCurrentItemRight = -1;
            return POSITION_NONE;
        }

        else{
            return super.getItemPosition(object);
        }
    }

    @Override
    public void setPrimaryItem(ViewGroup container, int position, Object object) {
        super.setPrimaryItem(container, position, object);
        currentRelativeLayout = (RelativeLayout) object;
    }

    @Override
    public Object instantiateItem(View container, final int position) {
//        RelativeLayout rl = (RelativeLayout) View.inflate(mContext, R.layout.item_pager_topic, null);
//        if (mList != null && mList.size() != 0) {
//            ((TextView)rl.findViewById(R.id.tv_topic_test)).setText(mList.get(position).getList_name());
//        }
//        ((ViewPager) container).addView(rl);
//        return rl;
        final RelativeLayout rl = (RelativeLayout) View.inflate(mContext, R.layout.item_topic_content, null);
        //添加tag设置，刷新时通过tag判断当前view
        rl.setTag(position);
        final CoverLoading cover = (CoverLoading) rl.findViewById(R.id.cover);

        final SwipeRefreshLayout srl = (SwipeRefreshLayout) rl.findViewById(R.id.srl_topic_content);

        final FooterListView flv = (FooterListView) rl.findViewById(R.id.flv_topic_content);

        //TODO 此处，根据数据判断要不要添加header
//        if(position == 0){
            flv.addRecommendHeader();
//        }

        final FeedListAdapter fAdapter = new FeedListAdapter(mContext,new ArrayList<RecommendFeed.DataBean.ListBean>(),
                mList.size()>0 ? mList.get(0).getId(): "");

        flv.setAdapter(fAdapter);

        fAdapter.setPostionCallBack(new FeedListAdapter.PositionCallBack() {
            @Override
            public void callBack(final int position) {

                boolean popShow = SPUtils.getPopShow();
                if (!popShow){
                    new Handler().postDelayed(new Runnable() {
                        @Override
                        public void run() {
                            int firstListItemPosition = flv.getFirstVisiblePosition();
                            int lastListItemPosition = firstListItemPosition
                                    + flv.getChildCount() - 1;

                            if (position < firstListItemPosition || position > lastListItemPosition) {
//                    flv.getAdapter().getView(position, null, flv);
                            } else {
                                final int childIndex = position - firstListItemPosition;
                                View childAt = flv.getChildAt(childIndex);
                                int [] xy = new int[2];
                                childAt.getLocationInWindow(xy);

                                int x = xy[0];
                                int y = xy[1];
                                showPopWindow(flv,childAt,x,y);
                                SPUtils.setPopShow();
                            }
                        }
                    },3000);

                }

            }
        });

        flv.setOnFooterClickListener(new FooterListView.FooterClickListener() {
            @Override
            public void onFooterClicked() {
                getTopicData(mList.get(position).getId(), rl, fAdapter,LOAD_MORE);
            }
        });
        flv.setOnLastItemVisiableListener(new FooterListView.LastItemVisiableListener() {
            @Override
            public void onLastItemVisiable() {
                getTopicData(mList.get(position).getId(), rl, fAdapter,LOAD_MORE);
            }
        });

        cover.setOnReloadClickListener(new CoverLoading.ReloadListener() {
            @Override
            public void onReloadClicked() {
                getTopicData(mList.get(position).getId(), rl, fAdapter,PULL_REFRESH);
            }
        });
        cover.setResult(CoverLoading.LoadingResult.LOADING);


        srl.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                getTopicData(mList.get(position).getId(), rl, fAdapter,PULL_REFRESH);
            }
        });

//        if(position==0){
            //TODO 如果为0，则认为是首页，所以数据应该是全部的
            getAllData(rl, fAdapter,position);
//        }else{
//            if(mList!=null && mList.size()>0){
//                getTopicData(mList.get(position).getId(),rl,fAdapter,PULL_REFRESH);
//            }
//        }

//FIXME Only the original thread that created a view hierarchy can touch its views.
        ((ViewPager) container).addView(rl);
        return rl;
    }

    private void showPopWindow(FooterListView flv, View childAt, int x, int y) {
        View view = View.inflate(mContext,R.layout.popupwindow,null);
        final PopupWindow popupWindow = new PopupWindow(view, ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
        view.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (popupWindow != null && popupWindow.isShowing()){
                    popupWindow.dismiss();
                }
            }
        });
//        popupWindow.showAtLocation(flv, Gravity.NO_GRAVITY,x,y);
        popupWindow.setFocusable(true);
        popupWindow.setOutsideTouchable(true);
        int dimension = mContext.getResources().getDimensionPixelSize(R.dimen.dp108);
        int dimension1 = mContext.getResources().getDimensionPixelSize(R.dimen.dp30);
        popupWindow.showAsDropDown(childAt,dimension1,dimension);

        new Handler().postDelayed(new Runnable() {
            @Override
            public void run() {
                if (popupWindow != null && popupWindow.isShowing()){
                    popupWindow.dismiss();
                }
            }
        },8000);
    }

    public void setList(List<RecommendData.DataBean.CategoryBean> list) {
        if (mList == null) {
            mList = new ArrayList<RecommendData.DataBean.CategoryBean>();
        }
        mList = list;
        notifyDataSetChanged();
    }

    public void addList(List<RecommendData.DataBean.CategoryBean> list) {
        if (mList == null) {
            mList = new ArrayList<RecommendData.DataBean.CategoryBean>();
        }
        mList.addAll(list);
        notifyDataSetChanged();
    }

    public void clearList() {
        if (mList != null) {
            mList.clear();
            notifyDataSetChanged();
        }
    }

    //TODO 可以抽取显示方式之后优化时候来做
    private static final int PULL_REFRESH = 0;
    private static final int LOAD_MORE = 1;
    private void getTopicData(String category_id, final RelativeLayout container,final FeedListAdapter adapter, final int code){
        //FIXME 说明，按照目前策略，服务端是会过滤掉相同feed的，所以说，现在是否传页数，是不care的
//        if(IS_FIRST) {
//            return;
//        }

        TreeMap<String,String> map = new TreeMap<>();
        map.put("category_id",category_id);
        map.put("pagesize","10");
        String index = String.valueOf(adapter.getCount()/10+1);
        map.put("page",index);

        HttpClient.post(SERVER + DISCOVER_FEED, map, new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                //TODO 如果是第一页，则
                //TODO 如果不是第一页则通知footer result
//                Log.e("TAG",e.getMessage().toString());

                ((Activity)mContext).runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        switch (code){
                            case PULL_REFRESH:
                                ((CoverLoading)container.findViewById(R.id.cover)).setResult(CoverLoading.LoadingResult.FAIL);
                                break;
                            case LOAD_MORE:
                                ((CoverLoading)container.findViewById(R.id.cover)).setResult(CoverLoading.LoadingResult.SUCCESS);
                                ((FooterListView) container.findViewById(R.id.flv_topic_content)).setResult(FooterListView.ActionResult.ERROR);
                                break;
                        }

                        if(container.findViewById(R.id.srl_topic_content) != null){
                            ((SwipeRefreshLayout) container.findViewById(R.id.srl_topic_content)).setRefreshing(false);
                        }
                    }
                });
            }

            //抽一下，没时间。。。
            @Override
            public void onResponse(final Call call, String response) {
//                String s = response.body().string();
                final RecommendFeed data = new Gson().fromJson(response,RecommendFeed.class);

                ((Activity)mContext).runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        switch (code){
                            case PULL_REFRESH:
                                //有数据
                                if(data != null && data.getData() != null && data.getData().getList() != null && data.getData().getList().size()>0){
                                    adapter.setList(data.getData().getList());
                                    ((CoverLoading)container.findViewById(R.id.cover)).setResult(CoverLoading.LoadingResult.SUCCESS);
                                    if(data.getData().getList().size()<=0){
                                        //no more
                                        ((FooterListView) container.findViewById(R.id.flv_topic_content)).setResult(FooterListView.ActionResult.NO_MORE);
                                    }else{
                                        ((FooterListView) container.findViewById(R.id.flv_topic_content)).setResult(FooterListView.ActionResult.HAS_MORE);
                                    }

                                }else{
                                    ((CoverLoading)container.findViewById(R.id.cover)).setResult(CoverLoading.LoadingResult.NULL);
                                    ((FooterListView) container.findViewById(R.id.flv_topic_content)).setResult(FooterListView.ActionResult.NO_MORE);
                                }
                                break;
                            case LOAD_MORE:
                                if(data != null && data.getData() != null && data.getData().getList() != null && data.getData().getList().size()>0){
                                    adapter.addList(data.getData().getList());
                                    ((CoverLoading)container.findViewById(R.id.cover)).setResult(CoverLoading.LoadingResult.SUCCESS);
                                    if(data.getData().getList().size()<=0){
                                        //no more
                                        ((FooterListView) container.findViewById(R.id.flv_topic_content)).setResult(FooterListView.ActionResult.NO_MORE);
                                    }else{
                                        ((FooterListView) container.findViewById(R.id.flv_topic_content)).setResult(FooterListView.ActionResult.HAS_MORE);
                                    }
                                }else{
                                    ((CoverLoading)container.findViewById(R.id.cover)).setResult(CoverLoading.LoadingResult.SUCCESS);
                                    ((FooterListView) container.findViewById(R.id.flv_topic_content)).setResult(FooterListView.ActionResult.NO_MORE);
                                }
                                break;
                        }

                        if((container.findViewById(R.id.srl_topic_content)) != null){
                            ((SwipeRefreshLayout) container.findViewById(R.id.srl_topic_content)).setRefreshing(false);
                        }
                    }
                });
            }
        });
    }



//    public void setRecommendData(List<RecommendData.DataBean.PlayCoversBean> recommendList,List<RecommendData.DataBean.AudioListBean> feedList){
//
//
//        IS_FIRST = false;
//    }


    private void getAllData(final RelativeLayout container, final FeedListAdapter adapter,final int position){

        final CoverLoading cover = (CoverLoading) container.findViewById(R.id.cover);
        final FooterListView flv = (FooterListView) container.findViewById(R.id.flv_topic_content);
//        List<RecommendData.DataBean.PlayCoversBean> recommendList;
//        List<RecommendData.DataBean.AudioListBean> feedList;
        final String category_id = mList.get(position).getId();
        TreeMap<String, String> map = new TreeMap<>();
        map.put("category_id",category_id);
        map.put("pagesize","10");

        HttpClient.post(HttpConfig.SERVER+HttpConfig.DISCOVER, map, new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {

                ((Activity)mContext).runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        if(cover!=null){
                            cover.setResult(CoverLoading.LoadingResult.FAIL);
                        }
                    }
                });
            }

            @Override
            public void onResponse(Call call, final String response)   {
//                final String s = response.body().string();
//                LogUtils.i("data",s);
                final RecommendData data = new Gson().fromJson(response,RecommendData.class);

                ((Activity)mContext).runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
//                        Log.e("TAG","response="+s);
                        if(data == null || data.getData() == null){
                            if(cover!=null){
                                cover.setResult(CoverLoading.LoadingResult.NULL);
                            }
                            return;
                        }

                        List<RecommendData.DataBean.PlayCoversBean> recommendList = data.getData().getPlay_covers();
                        List<RecommendData.DataBean.AudioListBean> feedList = data.getData().getAudio_list();
                        //跳转播单分类定位
                        flv.setRecommendHeaderData(recommendList,category_id);
                        //TODO TODO 添加banner数据获取接口
                        List<RecommendData.DataBean.BannerBean> banner = data.getData().getBanner();
                        for (int i=0;i<banner.size();i++){
                            if (!"1".equals(banner.get(i).getType()) && !"3".equals(banner.get(i).getType()) && !TextUtils.equals("4",banner.get(i).getType())){
                                banner.remove(i);
                                i--;
                            }
                        }
                        flv.setBannerData(banner);
                        flv.setF4(data.getData().getTool());

                        //-----FIXME cover坑，分清cover，先这样
                        if(feedList != null && feedList.size()>0){
                            adapter.setList(changeBean(feedList));
                            cover.setResult(CoverLoading.LoadingResult.SUCCESS);
                            if(feedList.size()<=0){
                                //no more
                                flv.setResult(FooterListView.ActionResult.NO_MORE);
                            }else{
                                flv.setResult(FooterListView.ActionResult.HAS_MORE);
                            }
                        }else{
                            cover.setResult(CoverLoading.LoadingResult.NULL);
                            flv.setResult(FooterListView.ActionResult.NO_MORE);
                        }
                        //------

                        if(cover!=null){
                            cover.setResult(CoverLoading.LoadingResult.SUCCESS);
                        }
                    }
                });


            }
        });
    }

    private List<RecommendFeed.DataBean.ListBean> changeBean(List<RecommendData.DataBean.AudioListBean> feedList){
        List<RecommendFeed.DataBean.ListBean> dataBeanList = new ArrayList<>();
        for(RecommendData.DataBean.AudioListBean temp : feedList){
            RecommendFeed.DataBean.ListBean bean = new RecommendFeed.DataBean.ListBean();
            bean.setPlaying(false);
            bean.setCategory_name(temp.getCategory_name());
            bean.setCollect(temp.getCollect());
            bean.setCover_id(temp.getCover_id());
            bean.setCover_name(temp.getCover_name());
            bean.setCover_pic(temp.getCover_pic());
            bean.setDuration(temp.getDuration());
            bean.setId(temp.getId());
            bean.setShare(temp.getShare());
            bean.setStar(temp.getStar());
            bean.setTitle(temp.getTitle());
            bean.setUrl(temp.getUrl());
            bean.setIs_share(temp.getIs_share());
            bean.setTag_id(temp.getTag_id());
            bean.setIs_unlocked(temp.getIs_unlocked());
            bean.setIs_collect(temp.isIs_collect());

            RecommendFeed.DataBean.ListBean.ShareInfoBean shareInfoBean = new RecommendFeed.DataBean.ListBean.ShareInfoBean();
            RecommendData.DataBean.AudioListBean.ShareInfoBean share_info = temp.getShare_info();
            shareInfoBean.setDesc(share_info.getDesc());
            shareInfoBean.setH5_url(share_info.getH5_url());
            shareInfoBean.setPic_url(share_info.getPic_url());
            shareInfoBean.setTitle(share_info.getTitle());

            bean.setShare_info(shareInfoBean);


            dataBeanList.add(bean);
        }
        return dataBeanList;
    }

    private int mCurrentItem = -1;
    private int mCurrentitemleft = -1;
    private int mCurrentItemRight = -1;
    public void updata(int currentItem,boolean isList,int position,String cover_id) {
        int count = getCount();
        this.mCurrentItem = currentItem;
        if (currentItem == 0){
            mCurrentitemleft = -1;
            mCurrentItemRight = 1;
        }else if(currentItem == count - 1){
            mCurrentitemleft = currentItem - 1;
            mCurrentItemRight = -1;
        }else{
            mCurrentitemleft = currentItem -1;
            mCurrentItemRight = currentItem + 1;
        }
        this.notifyDataSetChanged();
        refreshList(currentItem,position,cover_id);
        refreshHead(currentItem,position,cover_id);
    }

    private void refreshList(int mCurrentItem, int position, final String cover_id){
        ((Activity)mContext).runOnUiThread(new Runnable() {
            @Override
            public void run() {
                FooterListView flv = (FooterListView) currentRelativeLayout.findViewById(R.id.flv_topic_content);
                HeaderViewListAdapter head = (HeaderViewListAdapter) flv.getAdapter();
                FeedListAdapter adapter = (FeedListAdapter) head.getWrappedAdapter();

                List<RecommendFeed.DataBean.ListBean> list = adapter.getList();

                if (list!= null && list.size()>0){
                    int size = list.size();
                    for (int i=0;i<size;i++){
                        if (cover_id.equals(list.get(i).getCover_id())){
                            list.get(i).setIs_share("0");
                            list.get(i).setIs_unlocked("1");
                        }

                    }
                }

//        adapter.getList().get(position).setIs_unlocked("1");
//        adapter.getList().get(position).setIs_share("0");
                adapter.notifyDataSetChanged();
            }
        });

    }

    private void refreshHead(int mCurrentItem,int position,String cover_id){
        FooterListView flv = (FooterListView) currentRelativeLayout.findViewById(R.id.flv_topic_content);
        if (flv.getRecommendHeaderData() != null) {
            List<RecommendData.DataBean.PlayCoversBean> recommendHeaderData = flv.getRecommendHeaderData();
            if (recommendHeaderData != null && recommendHeaderData.size()>0){

                for (RecommendData.DataBean.PlayCoversBean bean : recommendHeaderData){
                    if (cover_id.equals(bean.getId())){
                        bean.setIs_share("0");
                        bean.setIs_unlocked("1");
                    }
                }

            }


//            flv.getRecommendHeaderData().get(position).setIs_share("0");
//            flv.getRecommendHeaderData().get(position).setIs_unlocked("1");
        }
        if (flv.getRVAdapter() != null) {
            flv.getRVAdapter().notifyDataSetChanged();
        }

    }

    public void notifyCollect(final String audioId) {
        ((Activity)mContext).runOnUiThread(new Runnable() {
            @Override
            public void run() {
                FooterListView flv = (FooterListView) currentRelativeLayout.findViewById(R.id.flv_topic_content);
                HeaderViewListAdapter head = (HeaderViewListAdapter) flv.getAdapter();
                FeedListAdapter adapter = (FeedListAdapter) head.getWrappedAdapter();

                List<RecommendFeed.DataBean.ListBean> list = adapter.getList();

                if (list!= null && list.size()>0){
                    int size = list.size();
                    for (int i=0;i<size;i++){
                        if (audioId.equals(list.get(i).getId())){
                            String collect = list.get(i).getCollect();
                            collect = (Integer.valueOf(collect)+1)+"";
                            list.get(i).setCollect(collect);
                            if(SPUtils.isLogined()){
                                list.get(i).setIs_collect(true);
                            }
                            break;
                        }

                    }
                }

//        adapter.getList().get(position).setIs_unlocked("1");
//        adapter.getList().get(position).setIs_share("0");
                adapter.notifyDataSetChanged();
            }
        });
    }
}
